const Question = require("../Models/question");
let mongoose=require('mongoose');

// 批量添加试题
exports.addQuestionPlus = function (data) {
    return new Promise(resolve => {
        // Question.collection.insertMany(data, {ordered: false},function (err, res) {
        //     resolve(err);
        //     //console.log(res)
        //     console.log('保存成功');
        // });
        Question.collection.insertOne(data, {ordered: false}, function (err, res) {
                resolve(err);
                console.log('保存成功');
        })
    })
};

// 获取试题列表
exports.getQuesList = async ctx => {
    let query = ctx.request.query;
    let page = Number(query.page);
    let limit = Number(query.limit);
    let selected = {};
    // 判断 query 参数是否> 2
    if (Object.keys(query).length > 2) {
        delete query.page;
        delete query.limit;
        selected = query;
    }
    // 查询总数
    const maxNum = await Question.estimatedDocumentCount((err, num) => err ? console.log(err) : num);
    await Question
        .find(selected)
        .skip(limit * (page - 1))
        .limit(limit)
        .then(data => {
            ctx.body = {
                status: 0,
                count: maxNum,
                data
            }
        })
        .catch(err => console.log(err));
};

// 删除试题
exports.delete = async ctx => {
    const data = ctx.request.body.data;
    let selected = [];
    if (data.length === 1) {
       selected = data;
    }else {
        // 调整数据格式
        for (let item in data) {
            selected.push({_id: data[item]._id});
        }
    }
    await Question.remove({_id: { $in: selected }})
        .then(data => {
            console.log('删除成功');
            ctx.body = {
                status: 200,
                data
            }
        }).catch(err => console.log(err));
};

// 试题数据更新
exports.update = async ctx => {
    let data = ctx.request.body;
    delete data.count;
    data._id = mongoose.Types.ObjectId(data._id);
    let quesContent = data.quesContent;
    let arr = [];
    for (let item in quesContent) {
        arr.push(quesContent[item])
    }
    data.quesContent = arr;
    await Question.collection.save(data)
        .then(data => {
            console.log(data);
            console.log('修改成功');
            ctx.body = {
                status: 200,
                data
            }
        })
};